package com.dg.river.module.base.presenter;


import com.dg.river.module.base.view.IBaseView;

import java.lang.ref.SoftReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;

/**
 * @作者：Hututu
 * @时间：2022/6/13 15:08
 * @描述：内容描述
 * @修改：修改内容
 * @Version:1.0
 */
public abstract class BasePresenterImpl<V extends IBaseView, M> implements IBasePresenter<IBaseView> {

    protected SoftReference<IBaseView> mReferenceView;
    protected V mProxyView;
    protected M mModel;

    @SuppressWarnings("unchecked")
    @Override
    public void attachView(IBaseView view) {
        // 软引用创建对象
        mReferenceView = new SoftReference<>(view);
        // 通过使用动态代理，做统一的逻辑判断，aop 思想
        mProxyView = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(), (proxy, method, args) -> {
            if (mReferenceView == null || mReferenceView.get() == null) {
                return null;
            }
            return method.invoke(mReferenceView.get(), args);
        });
        // 通过获得泛型类的父类，拿到泛型的接口实例，通过反射来实例化 model
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        if (type != null) {
            Type[] actualTypeArguments = type.getActualTypeArguments();
            try {
                mModel = (M) ((Class<?>) actualTypeArguments[1]).newInstance();
            } catch (IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void detachView() {
        mReferenceView.clear();
        mReferenceView = null;
    }

    protected V getView() {
        return mProxyView;
    }

    protected M getModel() {
        return mModel;
    }
}

